package com.hunan.api.catv.mq.consumer;

import com.google.gson.JsonObject;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.po.Tasks;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.tasks.TasksBiz;
import com.hunan.api.catv.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TasksConsumer {

    public static Logger log = LoggerFactory.getLogger(TasksConsumer.class);

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    TasksBiz tasksBiz;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConstants.tasks_queue, durable = "true"), exchange = @Exchange(value = MqConstants.tasks_exchange, durable = "true", type = "topic"), key = MqConstants.tasks_key))
    public void tasks(String msg) {
        log.info("[收到任务消息:{}]", msg);
        try {
            JsonObject msgJson = GsonUtils.fromJson(msg, JsonObject.class);
            Integer type = msgJson.get("type").getAsInt();
            String params = msgJson.get("params").getAsString();
            String name = msgJson.get("name").getAsString();
            Integer taskId = msgJson.get("taskId").getAsInt();
            Tasks tasks = new Tasks();
            tasks.setState(1);
            tasks.setTaskId(taskId);
            if (type == 1) {
                ServiceResult linkResult = memberBiz.export(name, taskId, params);
                if (linkResult.getStatus()) {
                    tasks.setLink(linkResult.getData().toString());
                    tasksBiz.update(tasks);
                }
            }
        } catch (Exception e) {
            log.error("[任务导出失败:{}]", e);
        }
    }
}
